package controller

import (
	"awesomeProject/lib"
	"github.com/gin-gonic/gin"
	"log"
)

var maxListNum = 50

func GetFriendList(c *gin.Context) {
	var req lib.GetFrdListReq
	if err := c.ShouldBindJSON(&req); err != nil {
		log.Println("read json fail")
		c.JSON(400, lib.GetFrdListResp{
			StatusCode: 0,
			StatusMsg:  "json invalid",
		})
		return
	}
	log.Println(req)
	ok, err := AuthId(req.Id, req.Token)
	if !ok || err != nil {
		log.Println("auth fail", err)
		c.JSON(400, lib.GetFrdListResp{
			StatusCode: 1,
			StatusMsg:  "your id or token is wrong",
		})
		return
	}
	frdList, cnt, err := GetAllFriend(req.Id)
	if err != nil {
		log.Println("get all friend fail or you don't have any friend yet")
		c.JSON(200, lib.GetFrdListResp{
			StatusCode: 1,
			StatusMsg:  "something wrong",
			Friends:    *frdList,
			SumNum:     cnt,
		})
		return
	}
	c.JSON(200, lib.GetFrdListResp{
		StatusCode: 2,
		StatusMsg:  "get friend list successfully",
		Friends:    *frdList,
		SumNum:     cnt,
	})
}

func GetAllFriend(selfId int64) (*[]lib.UserBrief, int, error) {
	var frdList []lib.UserBrief
	rows, err := pool.Query("select id_2 from public.relation where id_1=$1", selfId)
	if err != nil {
		log.Println("selfId invalid or you don't have any friend yet")
		return &frdList, 0, err
	}
	var cnt = 0
	for rows.Next() {
		var id int64
		if err = rows.Scan(&id); err != nil {
			log.Println("getallfriend fail")
			return &frdList, cnt, err
		}
		cnt++
		if cnt > maxListNum {
			log.Println("frdMaxNum excess")
			break
		}
		user, ok, err := SearchIdBrief(id)
		if !ok || err != nil {
			log.Println("id invalid in getallfriend")
			return &frdList, cnt, err
		}
		frdList = append(frdList, user)
	}
	return &frdList, cnt, nil
}
